<template>
    <div class="vaw-avatar-container">
        <a-dropdown trigger="hover" size="large" @select="handleSelect" popup-container="html">
            <div class="action-wrapper">
                <div class="avatar">
                    <a-avatar :size="30" shape="square" style="background-color: #fff;">
                        <img :src="userStore.avatar"
                        />
                    </a-avatar>
                </div>
                <span class="nick-name">
          {{ userStore.nickName }}
        </span>
                <icon-caret-down class="tip"/>
            </div>
            <template #content>
                <a-doption v-for="item of options" :key="item.key" :value="item.key" popup-container="html">
                    <template #icon>
                        <component :is="item.icon"/>
                    </template>
                    {{ item.label }}
                </a-doption>
            </template>
        </a-dropdown>
    </div>
    <a-modal :visible="pageData.changePwd" title="修改密码" @ok="changePasswordHandler"
             @cancel="pageData.changePwd = false">
        <a-form ref="formRef" :model="pwdData" layout="horizontal">
            <a-form-item label="原密码"
                         field="oldPwd"
                         :rules="[{validator: passwordValidator},{  required: true, message: '请输入原密码' }]"
                         :validate-trigger="['change', 'blur']">
                <a-input type="password"
                         v-model="pwdData.oldPwd" placeholder=""></a-input>
            </a-form-item>
            <a-form-item label="新密码"
                         field="pwd"
                         :rules="[{validator: passwordValidator},{  required: true, message: '请输入新密码' }]"
                         :validate-trigger="['change', 'blur']">
                <a-input type="password"
                         v-model="pwdData.pwd" placeholder=""></a-input>
            </a-form-item>
            <a-form-item label="新密码" field="confirmPwd"
                         :rules="[{validator: passwordValidator},{required: true, message: '请确认密码' }]"
                         :validate-trigger="['change', 'blur']">
                <a-input type="password"
                         v-model="pwdData.confirmPwd" placeholder=""></a-input>
            </a-form-item>
        </a-form>
    </a-modal>

    <a-modal :visible="pageData.userInfoVisible" title="个人信息"
             @cancel="pageData.userInfoVisible = false" :width="380">
        <template #footer>
            <a-button @click="pageData.userInfoVisible = false">取消</a-button>
        </template>
        <a-form :model="userDataFrom" >
            <a-form-item label="账号" label-col-flex="80px">

                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.userName}}</el-tag>
            </a-form-item>
            <a-form-item label="昵称" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.nickName}}</el-tag>
            </a-form-item>
            <a-form-item label="是否本集团" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.judgeGroup==0?'本集团':'外加工'}}</el-tag>
            </a-form-item>
            <a-form-item label="角色" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{`${userDataFrom.roleList}`}}</el-tag>
            </a-form-item>
            <a-form-item label="公司" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.firmName}}</el-tag>
            </a-form-item>
            <a-form-item label="部门" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.department}}</el-tag>
            </a-form-item>
            <a-form-item label="关联员工" label-col-flex="80px">
                <div style="width: 10px;"></div><el-tag class="ml-2" type="success">{{userDataFrom.empMap?.name}}</el-tag>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import {Message, Modal} from '@arco-design/web-vue'
    import {defineComponent, reactive, ref} from 'vue'
    import {
        IconUser as UserOutlined,
        IconPoweroff as LogoutOutlined,
        IconCaretDown as CaretDownOutlined,
        IconEdit as UpdatePassWordOutlined,
    } from '@arco-design/web-vue/es/icon'
    import useUserStore from '@/store/modules/user'
    import {useRouter} from 'vue-router'
    import {post} from "@/api/http";
    import md5 from "js-md5";
    import {FormInstance} from "@arco-design/web-vue/es/form";

    export default defineComponent({
        name: 'VAWavatar',
        components: {UserOutlined, LogoutOutlined, CaretDownOutlined, UpdatePassWordOutlined},
        setup() {
            const userStore = useUserStore()
            const pageData = reactive<{
                changePwd: boolean
                userInfoVisible: boolean
            }>({
                changePwd: false,
                userInfoVisible: false,
            });
            const pwdData = reactive({
                oldPwd: '',
                pwd: '',
                confirmPwd: ''
            })
            const options = [
                {
                  label: '个人信息',
                  key: 'personal-center',
                  icon: 'UserOutlined',
                },
                {
                    label: '修改密码',
                    key: 'updatePassWord',
                    icon: 'UpdatePassWordOutlined',
                },
                {
                    label: '退出登录',
                    key: 'logout',
                    icon: 'LogoutOutlined',
                },

            ]
            const userDataFrom:any = ref({})
            function personalCenter() {
                post({
                    url:"/admin/acl/user/findUserToken"
                }).then(({data})=>{
                    userDataFrom.value = data.data
                    pageData.userInfoVisible = true
                })
            }

            function logout() {
                Modal.confirm({
                    title: '提示',
                    content: '是否要退出当前账号？',
                    okText: '退出',
                    cancelText: '再想想',
                    onOk: () => {
                        userStore.logout().then(() => {
                            window.location.reload()
                        })
                    },
                })
            }

            function updatePassWord() {
                pwdData.confirmPwd = ''
                pwdData.pwd = ''
                pageData.changePwd = true
            }

            function handleSelect(key: string) {
                switch (key) {
                    case 'personal-center':
                        personalCenter()
                        break
                    case 'logout':
                        logout()
                        break
                    case 'updatePassWord':
                        updatePassWord()
                        break
                }
            }

            let formRef = ref<FormInstance>();
            const changePasswordHandler = () => {
                formRef.value?.validate().then((err) => {
                    if (!err) {
                        let oldPwd = md5(pwdData.oldPwd)
                        //3,8,20,27
                        const oldPwdArr = oldPwd.split('')
                       oldPwdArr.splice(3,0,'a')
                       oldPwdArr.splice(8,0,'b')
                       oldPwdArr.splice(20,0,'a')
                       oldPwdArr.splice(27,0,'b')
                        oldPwd = oldPwdArr.join('');
                        // 首先确认原密码是否正确
                        post({
                            url: "admin/acl/user/checkUserPassWordToken",
                            data: {password: oldPwd}
                        }).then((res: any) => {
                            // 返回200 可修改密码
                            if (res.code === 200) {
                                let pwd = md5(pwdData.pwd)
                                //3,8,20,27
                                const pwdarr = pwd.split('')
                                pwdarr.splice(3,0,'a')
                                pwdarr.splice(8,0,'b')
                                pwdarr.splice(20,0,'a')
                                pwdarr.splice(27,0,'b')
                                pwd = pwdarr.join('');
                                post({
                                    url: "admin/acl/user/updateUserPassWordToken",
                                    data: {
                                        password: pwd
                                    }
                                }).then((result: any) => {
                                    if (result.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.changePwd = false;
                                        Message.warning({
                                            content: '修改成功！5秒后跳转登陆页面.',
                                            duration: 5000
                                        });
                                        setTimeout(() => {
                                            userStore.logout().then(() => {
                                            }).finally(() => {
                                                window.location.reload()
                                            })
                                        }, 5000)
                                        return true
                                    } else {
                                        Message.error({
                                            content: '修改失败',
                                            duration: 5000
                                        });
                                        return false
                                    }
                                })
                            } else {
                                Message.error({
                                    content: '原密码输入不正确,不可修改密码!',
                                    duration: 5000
                                });
                                return false
                            }
                        })
                    }
                })
            }

            function passwordValidator(value: string,cb: Function) {
                if (pwdData.confirmPwd !== '' && pwdData.pwd !== '') {
                    return new Promise<void>(resolve => {
                        if (pwdData.confirmPwd != pwdData.pwd) {
                            cb('两次输入的密码不一致!');
                        }
                        resolve();
                    })
                }
            }

            return {
                formRef,
                passwordValidator,
                changePasswordHandler,
                userStore,
                options,
                handleSelect,
                updatePassWord,
                pwdData,
                pageData,
                userDataFrom
            }
        },
    })
</script>

<style lang="less" scoped>
    .vaw-avatar-container {
        .action-wrapper {
            display: flex;
            align-items: center;

            .avatar {
                display: flex;
                align-items: center;

                & > img {
                    border: 1px solid #f6f6f6;
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    border-radius: 50%;
                }
            }

            .nick-name {
                margin: 0 5px;

                .tip {
                    transform: rotate(0);
                    transition: transform @transitionTime;
                    margin-left: 2px;
                }
            }
        }
    }

    .vaw-avatar-container:hover {
        cursor: pointer;
        color: var(--primary-color);

        .tip {
            transform: rotate(180deg);
            transition: transform @transitionTime;
        }
    }
</style>
